package com.windward.vii.service;

import com.github.pagehelper.PageHelper;
import com.windward.vii.dao.entity.AssetUserAccount;
import com.windward.vii.dao.entity.Blacklist;
import com.windward.vii.dao.entity.User;
import com.windward.vii.dao.mapper.AssetUserAccountMapper;
import com.windward.vii.dao.mapper.BlacklistMapper;
import com.windward.vii.dao.mapper.UserMapper;
import com.windward.vii.service.rongcloud.RongCloudProxy;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Component
public class BlacklistService {

    @Resource
    BlacklistMapper blacklistMapper;
    @Resource
    UserMapper userMapper;
    @Resource
    AssetUserAccountMapper assetUserAccountMapper;
    @Resource
    RongCloudProxy rongCloudProxy;

    public boolean save(Blacklist blacklist) {
        Blacklist dbBlacklist = blacklistMapper.selectByUidAndBlackUid(blacklist.getUid(), blacklist.getBlackUid());
        if(dbBlacklist != null) {
            return true;
        }
        int row = blacklistMapper.insertSelective(blacklist);
        if(row > 0) {
            try {
                rongCloudProxy.getInstance().user.addBlacklist(String.valueOf(blacklist.getUid()), String.valueOf(blacklist.getBlackUid()));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return row > 0;
    }

    public boolean deleteByUidAndBlackUid(Long uid, Long blackUid) {
        int row = blacklistMapper.deleteByUidAndBlackUid(uid, blackUid);
        if(row > 0) {
            try {
                rongCloudProxy.getInstance().user.removeBlacklist(String.valueOf(uid), String.valueOf(blackUid));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return row > 0;
    }

    public Blacklist selectByUidAndBlackUid(Long uid, Long blackUid) {
        return blacklistMapper.selectByUidAndBlackUid(uid, blackUid);
    }

    public List<AssetUserAccount> getBlackList(Integer pageNum, Integer pageSize, Long uid) {
        pageNum = pageNum == null ? 1 : pageNum;
        pageSize = pageSize == null ? 10 : pageSize;
        PageHelper.startPage(pageNum, pageSize);

        List<Long> ids = blacklistMapper.getBlacklistByUid(uid);
        if(ids != null && ids.size() > 0) {
            return assetUserAccountMapper.getListByIds(ids);
        } else {
            return null;
        }
    }

}
